//本地数据
var app = getApp();

Page({
  data: {
    imgurl:app.globalData.imgurl,
    carts: [], // 购物车列表
    totalPrice: 0, // 总价，初始为0
    selectAllStatus: 0, // 全选状态，默认全选
    // 使用data数据对象设置样式名  
    minusStatus: 'disabled',
    startX: 0, //开始坐标
    startY: 0,
    isTouchMove: false, //默认全隐藏删除
    showcar: true,
    lens: [],
    shopid: '',
    ids: '',
    onOff: false
  },
  showModal: function (e) {
    console.log(e)
  },
  onLoad: function () {
  },
  onShow() {
    var that = this;
    //购物车列表
    that.getlist()
    // 每次打开全选状态为未选中
    this.setData({
      selectAllStatus:0
    })
  },

  //购物车列表
  getlist: function () {
    wx.showLoading({
      title: '正在加载',
    })
    var that = this;
    var openId = wx.getStorageSync('openId')
    wx.request({
      url: app.globalData.url + 'shopping?openid=' + openId,
      success: function (res) {
        var carts = res.data;
        console.log(carts)
        if (carts == null){
          carts = []
        }else if(carts.length>0){
          for (var i = 0; i < carts.length; i++) {
            carts[i].selected = 0
            for (var j = 0; j < carts[i].shop[0].shopping.length; j++) {
              var pro = carts[i].shop[0].shopping[j]
              carts[i].shop[0].shopping[j].selected = 0;
            }
          }
          that.summitBtn(carts) // 结算按钮颜色
          that.getTotalPrice(carts); // 计算总价
        }

        that.setData({
          carts: carts,
        })

      },complete:function(){
        wx.hideLoading()
      }
    })
  },
  // 跳转商铺
  toshop:function(e){
    var o = e.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/list/shop?shopid='+o.id,
    })
  },
  // 选择店铺事件
  selectShop:function(e){
    var o = e.currentTarget.dataset
    var carts = this.data.carts
    const selected = carts[o.shopidx].selected;
    carts[o.shopidx].selected = (selected + 1) % 2;
    var selectAllStatus = 1 //全选状态
    for (var i = 0; i < carts[o.shopidx].shop[0].shopping.length; i++) {
      carts[o.shopidx].shop[0].shopping[i].selected = carts[o.shopidx].selected
    }
    // 全选状态
    for (var k = 0; k < carts.length; k++) {
      var a = carts[k].selected
      selectAllStatus *= a
    }
    this.setData({
      carts: carts,
      selectAllStatus: selectAllStatus
    });
    this.summitBtn(carts) // 结算按钮颜色
    this.getTotalPrice(carts); // 计算总价
  },
  /**
   * 当前商品选中事件
   */

  selectList(e) {
    const o = e.currentTarget.dataset;
    var carts = this.data.carts;
    var selected = carts[o.shopidx].shop[0].shopping[o.goodidx].selected;
    carts[o.shopidx].shop[0].shopping[o.goodidx].selected = (selected + 1) % 2;

    var selectAllStatus = 1
    for (var i = 0; i < carts[o.shopidx].shop[0].shopping.length; i++) {
      if (i == 0) {
        var a = carts[o.shopidx].shop[0].shopping[i].selected;
        carts[o.shopidx].selected = a
      } else { 
        var b = carts[o.shopidx].selected 
        var c = carts[o.shopidx].shop[0].shopping[i].selected;
        carts[o.shopidx].selected = b * c
      }
    }
    for (var k = 0; k < carts.length; k++) {
      var a = carts[k].selected
      selectAllStatus *= a
    }
    this.setData({
      carts: carts,
      selectAllStatus: selectAllStatus
    });
    this.summitBtn(carts) // 结算按钮颜色
    this.getTotalPrice(carts);  // 计算总价
  },


  /**
   * 购物车全选事件
   */
  selectAll(e) {
    let selectAllStatus = this.data.selectAllStatus;
    selectAllStatus = !selectAllStatus;
    let carts = this.data.carts;
    let ids = this.data.ids;
    for (let i = 0; i < carts.length; i++) {
      carts[i].selected = selectAllStatus;
      for (let j = 0; j < carts[i].shop[0].shopping.length; j++){
        carts[i].shop[0].shopping[j].selected = selectAllStatus
      }
    }
    this.setData({
      selectAllStatus: selectAllStatus,
      carts: carts,
    });
    this.summitBtn(carts) // 结算按钮颜色
    this.getTotalPrice(carts); // 计算总价
  },

  /**
   * 绑定加数量事件
   */
  addCount(e) {
    var o = e.currentTarget.dataset
    let carts = this.data.carts;
    let num = parseInt(carts[o.shopidx].shop[0].shopping[o.goodidx].number);
    num = num + 1;
    carts[o.shopidx].shop[0].shopping[o.goodidx].number = num;
    var openId = wx.getStorageSync('openId');
    wx.request({
      url: app.globalData.url + 'shopping_xiugai?openid=' + openId +
      '&shopping_id=' + o.id + '&number=' + num,
      success: function (res) {
        console.log('加数量---', +res.data)
        wx.request({
          url: app.globalData.url + 'shopping?openid=' + wx.getStorageSync('openId'),
          success: function (res) {
            var carts = res.data;
            console.log(carts)
          }
        })
      } 
    })
    this.setData({
      carts: carts,
    });
    this.summitBtn(carts) // 结算按钮颜色
    this.getTotalPrice(carts); // 计算总价
  },

  /**
   * 绑定减数量事件
   */
  minusCount(e) {
    var o = e.currentTarget.dataset
    let carts = this.data.carts;
    let num = parseInt(carts[o.shopidx].shop[0].shopping[o.goodidx].number);
    if (num <= 1) {
      return false;
    }
    num = num - 1;
    carts[o.shopidx].shop[0].shopping[o.goodidx].number = num;
    var openId = wx.getStorageSync('openid');
    wx.request({
      url: app.globalData.url + 'shopping_xiugai?openid=' + openId +
      '&shopping_id=' + o.id + '&number=' + num,
      success: function (res) {
        console.log('减数量---', +res.data)
        wx.request({
          url: app.globalData.url + 'shopping?openid=' + wx.getStorageSync('openId'),
          success: function (res) {
            var carts = res.data;
            console.log(carts)
          }
        })
      }
    })
    this.setData({
      carts: carts,
    });
    this.summitBtn(carts) // 结算按钮颜色
    this.getTotalPrice(carts); // 计算总价
  },
  /**
   * 计算总价
   */
  getTotalPrice(carts) {
    let total = 0;
    var totalNum = 0;
    var totalYajin = 0
    for (let i = 0; i < carts.length; i++) {
      for (let j = 0; j < carts[i].shop[0].shopping.length; j++) {
        if (carts[i].shop[0].shopping[j].selected) { // 判断选中才会计算价格
          total += carts[i].shop[0].shopping[j].number * carts[i].shop[0].shopping[j].Product_zi.cuxiao_price; // 所有价格加起来
          totalNum += carts[i].shop[0].shopping[j].number*1
          totalYajin += carts[i].shop[0].shopping[j].number *carts[i].shop[0].shopping[j].Product_zi.yajin*1
        }
      }
    }
    this.setData({ // 最后赋值到data中渲染到页面
      totalPrice: total.toFixed(2),
      totalNum: totalNum,
      totalYajin: totalYajin.toFixed(2),
    });
  },
  //结算
  summit: function (e) {
    
    var length = this.data.length;
    var totalPrice = this.data.totalPrice;
    // if (totalPrice == '0.00' || totalPrice == '' || totalPrice == null || length == 0) {
    //   wx.showToast({
    //     title: '至少选择一个商品',
    //   })
    // } else {
      var types = this.data.types;
      var ids = this.getIds();
      wx.setStorage({
        key: 'ids',
        data: ids,
      })
      wx.navigateTo({
        url: '/pages/payment/zulin?ids=' + ids,
      })
      this.setData({
        ids: ''
      })
      console.log('---ids是清空了', this.data.ids)
    // }
  },
  getIds: function () {
    var carts = this.data.carts;
    var ids = []
    for (var i = 0; i < carts.length; i++) {
      for(var j = 0; j < carts[i].shop[0].shopping.length; j++){
        if (carts[i].shop[0].shopping[j].selected == 1) {
          ids.push(carts[i].shop[0].shopping[j].id)
        }
      }     
    }
    return ids.toString()
  },
  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.data.carts.forEach(function (v, i) {
      if (v.isTouchMove) //只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      carts: this.data.carts
    })
  },
  //滑动事件处理
  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index, //当前索引
      startX = that.data.startX, //开始X坐标
      startY = that.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
      //获取滑动角度
      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
    that.data.carts.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新数据
    that.setData({
      carts: that.data.carts
    })
  },
  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },

  //删除事件
  del: function (e) {
    var that = this;
    var openId = wx.getStorageSync('openId');
    var ids = this.getIds(this.data.carts)
    var id = e.currentTarget.dataset.id;
    wx.request({
      url: app.globalData.url + 'shopping_del?openid=' + openId + '&shopping_id=' + ids,
      success: function (res) {
        that.getlist()
      }
    })

  },
  // 切换删除
  manage: function () {
    var that = this;
    var carts = this.data.carts
    for (var i = 0; i < carts.length; i++) {
      carts[i].selected = 0
      for (var j = 0; j < carts[i].shop[0].shopping.length; j++) {
        var pro = carts[i].shop[0].shopping[j]
        carts[i].shop[0].shopping[j].selected = 0;
      }
    }
    this.getTotalPrice(carts)
    this.summitBtn(carts)
    this.setData({
      mstate: !this.data.mstate,// 切换删除
      carts: carts,
      selectAllStatus:0
    })
  },
  // 结算按钮颜色
  summitBtn:function(carts){
    var summitOn = 1;
    for (let i = 0; i < carts.length; i++) {
      for (let j = 0; j < carts[i].shop[0].shopping.length; j++) {
        var a = carts[i].shop[0].shopping[j].selected
        summitOn *= (a+1)%2
      }
    }
    this.setData({
      summitOn: summitOn
    })
  },
})